<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme() + "://"
          + request.getServerName() + ":" + request.getServerPort()
          + path + "/";
%>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=GB2312"/>
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scaleable=no"/>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta content="yes" name="apple-mobile-web-app-capable">
  <meta content="black" name="apple-mobile-web-app-status-bar-style">
  <meta content="telephone=no" name="format-detection">
    <title>数据源管理</title>
  <link rel="stylesheet" type="text/css" href="<%=basePath%>css/easyui.css" />
  <link rel="stylesheet" type="text/css" href="<%=basePath%>css/icon.css" />
  <script type="text/javascript" src="<%=basePath%>js/jquery.min.js"></script>
  <script type="text/javascript" src="<%=basePath%>js/jquery.easyui.min.js"></script>
  <script type="text/javascript" src="<%=basePath%>js/easyui-lang-zh_CN.js"></script>
  <script type="text/javascript" src="<%=basePath%>js/json2.js"></script>
</head>
<body>
<div id="main" class="easyui-layout" fit="true">
  <div id="center" region="center" style="background:#eee; overflow:hidden;border:0px;">
    <table toolbar="#div_toolbar" id="dataSource_grid" fitColumns="true" fit="true"  style="width:auto;height:100%"></table>
  </div>
  <div id="div_toolbar">
    <!-- 新增按钮-->
    <a id="new" class="easyui-linkbutton" title="新建" iconCls="icon-add" plain="true">新建</a>
    <!-- 保存按钮-->
    <a id="save" class="easyui-linkbutton" style="display: none;" title="保存" iconCls="icon-save" plain="true">保存</a>
    <!-- 删除按钮-->
    <a id="del" class="easyui-linkbutton" title="删除" iconCls="icon-cancel" plain="true">删除</a>
    <!-- 刷新按钮-->
    <a id="ref" class="easyui-linkbutton" title="刷新" iconCls="icon-reload" plain="true">刷新</a>
    <!-- 手动备份按钮-->
    <a id="task" class="easyui-linkbutton" style="display: none;" title="备份" iconCls="icon-bank" plain="true">备份</a>
    <%--<input type="text" id="filed" class="easyui-textbox" style="border:1px solid #94BAE7;"/>--%>
    <%--<a id="search" style="color: #313031; border:1px solid #E7F3F7;" class="easyui-linkbutton" title="查询" iconCls="icon-search" plain="true"></a>--%>
  </div>
</div>
</body>
<script type="text/javascript">
  var offset = 1;
  var limit = 20;
  var dataGrid,editRow,rowIndex;
  var driverObject = new Object();
  var type = [{value:'MYSQL',text:'MYSQL'},{value:'ORACLE',text:'ORACLE'}];
  function initControl() {//初始化属性选项控件类型
    driverObject.MYSQL = 'com.mysql.jdbc.Driver';
    driverObject.ORACLE = 'oracle.jdbc.driver.OracleDriver';
  }
  $(function (){
    initControl();
    dataGrid = $('#dataSource_grid').datagrid({//表格数据
      singleSelect:true,
      pagination:true,
      url:'<%=basePath%>datasource/pages?newDate='+new Date(),//任务数据请求
      queryParams:{page:offset,rows:limit,name:''},
      columns:[[
        {field:'ck',checkbox:true},
        {field:'id',title:'标示',hidden:true,align:"center",sortable:true},
        {field:'dsName',title:'数据源别名',align:"center",width:'12%',sortable:true,editor:'text'},
        {field:'dsType',title:'数据库类型',align:'center',width:'12%',sortable:true,editor:{
          type:'combobox',
          options:{
            valueField:'text',
            textField:'value',
            editable:false,
            panelHeight:100,
            mode:'local',
            data:type
          }}},
        {field:'dsDriver',title:'数据库驱动',hidden:true,align:'center',width:'15%',sortable:true,formatter:function(value,rowData,rowIndex){
          return driverObject[rowData.dsType];
        }},
        {field:'url',title:'IP地址：端口号',align:'center',width:'20%',resizable:true,editor:'text'},
        {field:'dsUsername',title:'用户名',align:'center',width:'14%',sortable:true,editor:'text'},
        {field:'dsPassword',title:'密码',align:'center',width:'12%',sortable:true,editor:'text'},
        {field:'dsDesc',title:'数据库名',align:'center',width:'12%',sortable:true,editor:'text'},
        {field:'createtime',title:'创建时间',align:'center',width:'10%',resizable:true},
        {field:'operate',title:'操作',align:'center',width:'8%',formatter:function(value,rowData,rowIndex){
          return '<div id="update_'+rowIndex+'"><a href="#" id="edit'+rowIndex+'" onclick="updateData('+rowIndex+')">编辑</a></div>';
        }}
      ]]
//      ,onDblClickCell:function(index,field,value){//grid双击事件
//        $(this).datagrid('beginEdit', index);
//        if(editRow!=undefined && editRow != index){
//          dataGrid.datagrid("endEdit", editRow);
//        }
//        var ed = $(this).datagrid('getEditor', {index:index,field:field});
//        $(ed.target).focus();
//        editRow = index;
//      }
    });

    //grid的分页信息
    $('#dataSource_grid').datagrid('getPager').pagination({//分页对象
      pageSize: 25,
      beforePageText: '第',
      afterPageText: '页    共 {pages} 页',
      displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录',
      pageList:[25,50,75,100,150]
    });

    $("#del").bind("click",function(){//删除按钮
      var rows = dataGrid.datagrid("getSelected");
      rowIndex = dataGrid.datagrid("getRowIndex", rows);
      if(rows != undefined) {
        $.messager.confirm("提示","是否删除该数据",function(res){
          if(res){
            if(rows.id == null || rows.id == '') {
              dataGrid.datagrid("deleteRow", rowIndex);
            } else {
              var id = parseInt(rows.id);
              $.ajax({
                url:"<%=basePath%>datasource/delete/"+id,
                type:"delete",
                timeout:20000,
                data:{
                  id:id
                },
                success:function(res){
                  if(res.code == 0) {
                    dataGrid.datagrid("deleteRow", rowIndex);
                  }
                  $.messager.show({
                    title:'提示',
                    width:250,
                    height:140,
                    msg:res.msg
                  });
                },
                error: function (error) {
                  $.messager.show({
                    title:'提示',
                    width:250,
                    height:140,
                    msg:"系统繁忙，请稍后再试！"
                  });
                }
              });
            }
          }
        });
      } else {
        $.messager.show({
          title:'提示',
          width:250,
          height:140,
          msg:"没有选中行~~~！"
        });
      }
    });

    $("#new").bind("click", function() {//新建按钮
      var row ={id:'',dsName:'',dsDriver:'com.mysql.jdbc.Driver',
        url:'localhost:3306',dsUsername:'root',dsPassword:'',dsType:'MYSQL',dsDesc:'',createtime:''};
      dataGrid.datagrid("appendRow", row);
      var rowIndex = dataGrid.datagrid("getRowIndex", row);
      updateData(rowIndex);
    });

    $("#ref").bind("click",function() {//刷新按钮
      dataGrid.datagrid('load',{page:offset,rows:limit,name:''});
    });

    $("#task").bind("click",function(){
      var opt = $("#task").linkbutton("options");
      if(!opt.disabled) {
        $("#task").linkbutton({disabled:true});
        $.ajax({
          url:"<%=basePath%>task/task",
          type:"post",
          timeout:20000,
          success:function(res){
            $.messager.show({
              title:'提示',
              width:250,
              height:140,
              msg:res.msg
            });
            $("#task").linkbutton({disabled:false});
          },
          error: function (error) {
            $.messager.show({
              title:'提示',
              width:250,
              height:140,
              msg:"系统繁忙，请稍后再试！"
            });
            $("#task").linkbutton({disabled:false});
          }
        });
      }
    });

    $("#save").bind("click", function(){//保存按钮
      var opt = $("#save").linkbutton("options");
      if(!opt.disabled){
        $("#save").linkbutton({disabled:true});
        if (editRow != undefined) {
          dataGrid.datagrid("endEdit", editRow);
        }
        var modified =dataGrid.datagrid('getRows');
        if(modified != null && modified.length > 0){//批量
          $.ajax({
            url:"<%=basePath%> /saveData",
            type:"post",
            data:{
              jsonObj:JSON.stringify(modified)
            },
            timeout:20000,
            success:function(res){
              console.log(res)
              $.messager.show({
                title:'提示',
                width:250,
                height:140,
                msg:res.msg
              });
              $("#save").linkbutton({disabled:false});
              if(res.code == 0) {
                dataGrid.datagrid('load',{page:offset,rows:limit,name:''});
              }
            },
            error: function (error) {
              $.messager.show({
                title:'提示',
                width:250,
                height:140,
                msg:"系统繁忙，请稍后再试！"
              });
              $("#save").linkbutton({disabled:false});
            }
          });
        } else {
          $.messager.alert("提示","没有任何保存数据！");
          $("#save").linkbutton({disabled:false});
        }
      }
    });
  });

  /**编辑行获得焦点**/
  function updateData(index){
    if("#save" + index){
      $("#save"+index).remove();
    }
    $("#edit"+index).hide();
    $("#update_" + index).append("<a id='save"+index+"' onclick=saveData("+index+") href='#'>保存</a>");
    $('#dataSource_grid').datagrid('beginEdit', index);
    if(editRow!=undefined && editRow != index){
      $("#save"+editRow).remove();
      dataGrid.datagrid("endEdit", editRow);
    }
    editRow = index;
  }

  /**保存行编辑**/
  function saveData(index) {
    if (editRow != undefined) {//判断编辑行是否是空
      dataGrid.datagrid("endEdit", editRow);
    }
    var modified =dataGrid.datagrid('getRows');//获取所以数据源
    if(modified != null && modified.length > 0) {
      $.ajax({
        url:'<%=basePath%>datasource/save',
        type:'post',
        data:{
          json:JSON.stringify(modified[index])
        },
        success:function (res){
          console.log(res)
          if(res.code == 0){
            $("#edit"+index).show();
            dataGrid.datagrid('load',{page:offset,rows:limit,name:''});
            $.messager.show({
              title:'提示',
              width:250,
              height:140,
              msg:res.message
            });
          } else {
            $.messager.show({
              title:'提示',
              width:250,
              height:140,
              msg:"<div class='messager-icon messager-error'></div><div>"+ res.message +"</div>"
            });
            updateData(index);
          }

        }
      });
    }

  }

  /**
    *获取分页数据
    * @param params
   */
  function getDataSource(params){
    $.ajax({
      url:'<%=basePath%>datasource/pages',
      type:'POST',
      data:params,
      timeout:20000,
      success:function(res){
        return res;
      },
      error: function (error) {
        $.messager.alert("系统繁忙，请稍后再试！");
      }
    });
  }

</script>
</html>
